<?php
/**
 * Performance Optimization Service
 * Provides caching, query optimization, and response speed improvements
 */

namespace app\common\service;

use think\Db;

class PerformanceService
{
    const CACHE_TTL_SHORT = 300;
    const CACHE_TTL_MEDIUM = 900;
    const CACHE_TTL_LONG = 3600;
    
    /**
     * Get cached apps list for user with optimized query
     */
    public static function getCachedAppsList($userId, $refresh = false)
    {
        $cacheKey = "apps_list_user_{$userId}";
        
        if (!$refresh) {
            $cached = cache($cacheKey);
            if ($cached !== null) {
                return $cached;
            }
        }
        
        // Optimized query with specific fields and indexes
        $apps = Db::name('apps')
            ->where('user_id', $userId)
            ->where('is_delete', 0)
            ->field('id, name, appkey, status, created_at, updated_at')
            ->order('created_at', 'desc')
            ->select();
        
        cache($cacheKey, $apps, self::CACHE_TTL_MEDIUM);
        return $apps;
    }
    
    /**
     * Get cached app statistics
     */
    public static function getCachedAppStats($appkey, $refresh = false)
    {
        $cacheKey = "app_stats_{$appkey}";
        
        if (!$refresh) {
            $cached = cache($cacheKey);
            if ($cached !== null) {
                return $cached;
            }
        }
        
        $stats = [
            'total_requests' => self::getAppRequestCount($appkey),
            'today_requests' => self::getAppRequestCount($appkey, date('Y-m-d')),
            'error_rate' => self::getAppErrorRate($appkey),
            'avg_response_time' => self::getAppAvgResponseTime($appkey)
        ];
        
        cache($cacheKey, $stats, self::CACHE_TTL_SHORT);
        return $stats;
    }
    
    /**
     * Clear user cache
     */
    public static function clearUserCache($userId)
    {
        $cacheKeys = [
            "apps_list_user_{$userId}",
            "user_membership_{$userId}",
            "dashboard_data_{$userId}_7",
            "dashboard_data_{$userId}_30",
            "dashboard_data_{$userId}_90"
        ];
        
        foreach ($cacheKeys as $key) {
            cache($key, null);
        }
    }
    
    /**
     * Clear app cache
     */
    public static function clearAppCache($appkey)
    {
        $cacheKeys = [
            "app_stats_{$appkey}",
            "sdk_usage_{$appkey}_daily",
            "sdk_usage_{$appkey}_weekly"
        ];
        
        foreach ($cacheKeys as $key) {
            cache($key, null);
        }
    }
    
    /**
     * Optimized query methods
     */
    private static function getAppRequestCount($appkey, $date = null)
    {
        $query = Db::name('sdk_usage_logs')->where('appkey', $appkey);
        
        if ($date) {
            $query->where('created_at', '>=', $date . ' 00:00:00')
                  ->where('created_at', '<=', $date . ' 23:59:59');
        }
        
        return $query->count();
    }
    
    private static function getAppErrorRate($appkey)
    {
        $total = Db::name('sdk_usage_logs')->where('appkey', $appkey)->count();
        $errors = Db::name('sdk_usage_logs')->where('appkey', $appkey)->where('status', 'error')->count();
        
        return $total > 0 ? round(($errors / $total) * 100, 2) : 0;
    }
    
    private static function getAppAvgResponseTime($appkey)
    {
        return Db::name('sdk_usage_logs')
            ->where('appkey', $appkey)
            ->where('response_time', '>', 0)
            ->avg('response_time') ?: 0;
    }
}